package de.lmu.ifi.pst.uwejsf.framework;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class UWEPhaseListener implements PhaseListener {

	private static final long serialVersionUID = -6710664393268282507L;

	private AbstractUWENavigator getNavigator() {
		return (AbstractUWENavigator) ExpressionHelpers
				.resolveValue("#{uweNavigator}");
	}

	@Override
	public void afterPhase(PhaseEvent pe) {
		if (pe.getPhaseId() == PhaseId.APPLY_REQUEST_VALUES) {

			getNavigator().setCurrentViewID(getCurrentViewId(pe.getFacesContext()));
			
		} else if (pe.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
			// Navigation in AbstractUWENavigator.forward() has completed. Set current view again. 
			getNavigator().setCurrentViewID(getCurrentViewId(pe.getFacesContext()));
			getNavigator().handleView();
			getNavigator().handleRegisteredSubmitOrder();
		}
	}

	private String getCurrentViewId(FacesContext facesContext) {
		String currentViewID = facesContext.getViewRoot().getViewId();
		// remove start ("/") and end (".jsp")
		currentViewID = currentViewID.substring(1, currentViewID.length() - 4);
		return currentViewID;
	}

	@Override
	public void beforePhase(PhaseEvent pe) {

		getNavigator().incEvaluationToken();
	}

	@Override
	public PhaseId getPhaseId() {

		return PhaseId.ANY_PHASE;
	}

}
